﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Configuration;

namespace adlaunch
{

    public partial class Form1 : Form
    {
        [DllImport("user32.dll", EntryPoint = "SetWindowPos", SetLastError = true)]
        static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
       
        [DllImport("User32.dll", EntryPoint = "SetForegroundWindow")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll", SetLastError = true)]
        static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, int hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("User32.dll")]
        static extern int GetWindowText(IntPtr handle, StringBuilder text, int MaxLen);

        // PostMessage
        uint WM_LBUTTONDOWN = 0x201;
        uint WM_LBUTTONUP = 0x202;
        uint WM_RBUTTONDOWN = 0x0204;
        uint WM_RBUTTONUP = 0x0205;
        uint WM_MOUSEMOVE = 0x0200;

        uint WM_KEYDOWN = 0x0100;
        uint WM_KEYUP = 0x0101;

        int KEY_ENTER = 0x0D;
        int KEY_F11 = 0x7A;

        String[] urls = new String[2];

        //public string exe = @"C:\Users\rome\AppData\Local\Google\Chrome\Application\chrome.exe";
        public string exe = @"C:\Users\rome\Desktop\";


        Boolean AUTO = false;

        public Form1()
        {
            InitializeComponent();

            string chrome = ConfigurationSettings.AppSettings["chrome"];
            string url1 = ConfigurationSettings.AppSettings["url1"];
            string url2 = ConfigurationSettings.AppSettings["url2"];

            if (chrome != null && !chrome.Equals(""))
            {
                this.exe = chrome;

            }

            if (url1 != null && !url1.Equals(""))
            {
                this.textBox1.Text = url1;
            }

            if (url2 != null && !url2.Equals(""))
            {
                this.textBox2.Text = url2;
            }
            this.textBox3.Text = this.exe;
        }
        public Form1(bool auto)
            : this()
        {
            AUTO = auto;
            //#if DEBUG

            //#else
            //            if(AUTO){
            //                Application.DoEvents();
            //                Thread.Sleep(5000);
            //                Application.DoEvents();
            //                this.Shown += new System.EventHandler(this.button1_Click);

            //            }
            //#endif
        }


        private void button1_Click(object sender, EventArgs e)
        {

            closeAll();
            Thread.Sleep(3000);
            init();
            //   find();
            display();
            // start(200 ,1000,400);

        }
        private void init()
        {
            urls[0] = this.textBox1.Text;
            urls[1] = this.textBox2.Text;
        }

        

        private IntPtr find(string name )
        { 
            //System.Diagnostics.Process[] allProcesses = System.Diagnostics.Process.GetProcessesByName("chrome");
            System.Diagnostics.Process[] allProcesses = System.Diagnostics.Process.GetProcesses();
            //log("all:" + allProcesses.Length);
            for (int i = 0; i < allProcesses.Length; i++)
            {

                if (allProcesses[i].ProcessName == "node")
                {
                    //log(allProcesses[i].ProcessName);

                    if (allProcesses[i].MainWindowHandle != IntPtr.Zero)
                    {
                        //log(allProcesses[i].Handle.ToString());
                        //log(allProcesses[i].Id.ToString());

                        StringBuilder text = new StringBuilder(512);
                        GetWindowText(allProcesses[i].MainWindowHandle, text, 512);
                        //log(name + "||"+ text);
                        if (name.Equals(text.ToString()))
                        {
                            log(allProcesses[i].MainWindowHandle.ToString() + "||" + text);
                            return allProcesses[i].MainWindowHandle;
                        }
                    }
                }
            }
            return IntPtr.Zero;
        }

        private void display()
        {

            Screen[] s = Screen.AllScreens;
            this.loginfo.Text += "共" + s.Length + "块屏幕\r\n";


            Rectangle[] ScreensRect = new Rectangle[s.Length];
            for (int i = 0; i < s.Length; i++)
            {

                this.loginfo.Text += "第" + s[i].DeviceName + "块屏幕\r\n";
                ScreensRect[i] = s[i].WorkingArea;

                this.loginfo.Text += "Height :" + ScreensRect[i].Height + "\r\n";
                this.loginfo.Text += "Width :" + ScreensRect[i].Width + "\r\n";

                this.loginfo.Text += "X :" + ScreensRect[i].X + "\r\n";

                this.loginfo.Text += "Y :" + ScreensRect[i].Y + "\r\n";
                Application.DoEvents();
                this.start(ScreensRect[i].X, ScreensRect[i].Width, ScreensRect[i].Height, urls[i]);

            }

            //int iX = ScreensRect[1].X;
            //int iY = ScreensRect[1].Y;
        }

        private void start(int x, int w, int h, String url)
        {

            System.Diagnostics.Process p = new System.Diagnostics.Process();

            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;

         
            Application.DoEvents();
            p.StartInfo.FileName = exe + url + @"\app.exe";//需要启动的程序名       
            // p.StartInfo.Arguments = "http://www.baidu.com  --kiosk --new-window";//启动参数  
            //p.StartInfo.Arguments = url ;//启动参数  
            p.Start();//启动       

            //p.WaitForInputIdle();
            //p.WaitForExit(3000);
            //try
            //{
            //    do
            //    {
            //        Thread.Sleep(100);
            //        p.Refresh();
            //    }
            //    while (p.MainWindowHandle == IntPtr.Zero && !p.HasExited);
            //}
            //catch (Exception e)
            //{
            //    log(e.ToString());
            //}

            //IntPtr hMainWindow = IntPtr.Zero;

            //if (!p.WaitForExit(5000))
            //{

            //    if (!p.HasExited)
            //    {
            //        hMainWindow = p.MainWindowHandle;
            //        // Do whatever you need to do with hwnd
            //    }
            //}

            //log(hMainWindow.ToString());

            //System.Diagnostics.Process p = new System.Diagnostics.Process();
            //p.StartInfo.FileName = url;
            //p.Start(url);
            //System.Diagnostics.Process p = System.Diagnostics.Process.Start(url); 
            //p.WaitForInputIdle();

            Application.DoEvents();
            Thread.Sleep(10000);
            Application.DoEvents();

            //p.WaitForInputIdle();
            //IntPtr hMainWindow = p.MainWindowHandle;

            //p.CloseMainWindow();
            //MessageBox.Show(hMainWindow.ToString());
            //p.Handle;
            //IntPtr hMainWindow = Process.GetCurrentProcess().MainWindowHandle;
            //SetWindowPos(hMainWindow, (IntPtr)(0), 1024, 0, 1024, 768, 0x0040);

            //p.WaitForExit(3000);


            //IntPtr hMainWindow = p.MainWindowHandle;

            IntPtr hMainWindow = find(url);


            //log(hMainWindow.ToString() + " x:" + x + " w:" + w + " h:" + h);
            //MessageBox.Show(hMainWindow.ToString());
            SetWindowPos(hMainWindow, (IntPtr)(0), x, 0, w, h, 0x0040);

            //SetWindowPos(hMainWindow, (IntPtr)(0), 1024, 0, 1024, 768, 0x0040);
            //Application.DoEvents();
            //Thread.Sleep(1000);

            Thread.Sleep(1000);
            SetForegroundWindow(hMainWindow);
            //IntPtr child = FindWindowEx(hMainWindow, 0, "AppjsWindow", null);

            //child = FindWindowEx(child, 0, "Chrome_RenderWidgetHostHWND", null);

            // IntPtr child = hMainWindow;
            //Thread.Sleep(5000);
            //log(child.ToString() + " x:" + x + " w:" + w + " h:" + h);

            //PostMessage(child, WM_KEYDOWN, KEY_F11, 0);
            //Thread.Sleep(100);
            //PostMessage(child, WM_KEYUP, KEY_F11, 0);
            //Thread.Sleep(200);
            //PostMessage(hMainWindow, WM_KEYDOWN, KEY_F11, 0);
            //Thread.Sleep(200);
            //PostMessage(hMainWindow, WM_KEYUP, KEY_F11, 0);
            //Thread.Sleep(10000);
        }

        private void log(string str)
        {
            this.loginfo.Text += str + "\r\n";
        }

        private void button2_Click(object sender, EventArgs e)
        {
           find("weibo");
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// 关闭IE窗口
        /// </summary>
        private void closeAll()
        {
            Process[] process = Process.GetProcesses();
            for (int i = 0; i < process.Length; i++)
            {
                if (process[i].ProcessName.ToLower() == "node")
                {
                    try
                    {
                        process[i].Kill();
                        process[i].Close();
                        Application.DoEvents();
                        Thread.Sleep(300);
                    }
                    catch
                    {
                    }
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (AUTO)
            {
                //   this.Shown += new System.EventHandler(this.button1_Click);
                this.button1_Click(sender, e);
                //   this.timer1.Enabled = false;
                //   this.timer1.Stop();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //this.timer1.Start();
            System.Timers.Timer timer1 = new System.Timers.Timer();
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
            timer1.Interval = 5000;
            timer1.AutoReset = false;
            timer1.Enabled = true;
            timer1.Start();
        }
    }
}
